<?php
require_once($common_data_server.'modules/shop/shop.php'); 

/********************************************************
Project: Оформление заказа
Author:  Холодий Андрей
Version: 1.0
Date:    28.08.2003 14:57
********************************************************/

/**
  * Оформление заказа
  * @author  Холодий Андрей
  * @version 1.1
  * @copyright Copyright 2003, РБК СОФТ
  * @package E-shop
  * @subpackage orders
  */

class orders extends shop {

  var $client_id;

  /****************** content_init ************************************/
  function content_init() {
	/* 
	  Инициализация модуля.
	*/	
	global $common_data_server;
	$this -> path_tmpl = "{$common_data_server}module_templates/orders/{$this -> view_param['template']}/";
    $this -> publishedCurrency = $this -> getPublishedCurrency();
    $this -> mainCurrency = $this -> getMainCurrency();
	$this -> tmpl = new vlibTemplate();

	//НАЧАЛО. Проверка переменных из QUERY_STRING
	//echo $this -> q_param['payment_id'] . "= payment_id";
	if ( !is_numeric($this -> q_param['payment_id']) ) $this -> q_param['payment_id'] = '';
	if ( !is_numeric($this -> q_param['delivery_address_id']) ) $this -> q_param['delivery_address_id'] = '';
	if ( isset($this -> q_param['step']) && 
		 (!is_numeric($this -> q_param['step']) || 
		  $this -> q_param['step'] < 1 || 
		  $this -> q_param['step'] > 3) ) $this -> q_param['delivery_address_id'] = '';	
	//КОНЕЦ. Проверка переменных из QUERY_STRING
	
	session_start();

	//Корзина пуста
	if ( !isset($_SESSION['cart']) || !count($_SESSION['cart']->items) ) $filename = 'empty_basket';
	else 
		foreach ( $_SESSION['cart']->items as $item )
			if ( !$item['status'] ) $isProductsInBasket = true;
	
	if ( !$isProductsInBasket ) $filename = 'empty_basket';
	
	//Не аутентифицирован
	elseif ( !$this -> modeAuth() && !$filename)  $filename = 'auth';
	//Задается вопрос о желании продолжить оформление заказа или начать заново
	elseif ( $_SESSION['order']->step > 1 && 
			 !isset($this -> q_param['step']) && 
			 !isset($this -> q_param['is_order'])) $filename = 'question';
	//Оформление заказа
	elseif ( $this -> modeAuth() && !$filename) {
		
		$client_id = $this -> modeAuth();
		$this -> client_id = ( is_array($client_id) ? $client_id[0]['CLIENT_ID'] : $_COOKIE['client_id'] );
		
		if ( isset($this -> q_param['answer']) && !$this -> q_param['answer'] ) unset($_SESSION['order']);
		
		if ( !$_SESSION['order'] || $_COOKIE['client_id'] <> $_SESSION['order']->client_id ) $_SESSION['order'] = new order;
		
		//Переход по ссылкам (шаги)
		if ( $this -> q_param['step'] && $_SESSION['order']->step > $this -> q_param['step'] ) 
			$_SESSION['order']->step = $this -> q_param['step'];
		
		if ( $_SESSION['order']->step == 1 ) $filename = ($this -> step1() ? 'step2' : 'step1');
		if ( $_SESSION['order']->step == 2 ) $filename = ($this -> step2() ? 'step3' : 'step2');
		if ( $_SESSION['order']->step == 3 ) $filename = ($this -> step3() ? 'thanx' : 'step3');
	}

    $this -> path_tmpl .= $filename . '.vtmpl';
    
    if ( !file_exists( $this -> path_tmpl ) ) {
	   		$this -> body="Шаблон отсутствует: " . $this -> path_tmpl;
	   		return 0;
	}

    $this -> tmpl -> newTemplate( $this -> path_tmpl );
	
	//echo $_COOKIE['random_number'];
	//echo " client_id=" . $_COOKIE['client_id'];	
	$this -> tmpl -> setVar( "_tarea", $this -> tarea_id);
	
    $this -> body = $this -> tmpl->grab();
  }

  /***************************** Шаг 3 *******************/
  function step3() {
  	
  	if ( $this -> q_param['comments'] ) $_SESSION['order']->comments = $this -> q_param['comments'];
  	
	  	$this -> tmpl -> setVar('FIO', $_SESSION['order']->fio);
	  	$this -> tmpl -> setVar('ADDRESS', $_SESSION['order']->address);
	  	$this -> tmpl -> setVar('TELEPHONE', $_SESSION['order']->telephone);
	  	$this -> tmpl -> setVar('PAYMENT_NAME', $_SESSION['order']->payment_name);
	  	$this -> tmpl -> setVar('_comments', $_SESSION['order']->comments);
	  	$this -> tmpl -> setVar('_note', $_SESSION['order']->note);
	  	
	  	foreach ($_SESSION['cart']->items as $item) 
	  		if ( !$item['status'] ) $set_product .= intval($item['id']) . ", ";
	  		
		$product_arr =  sql_select("select * from PRODUCT where
										CONTENT_ID in (" . substr($set_product, 0, strlen($set_product) - 2) . ") and
										LANG_ID = " . intval($this -> lang_id). " and
										VERSION = " .intval($this -> version));
		
		for ($i = 0; $i < count($product_arr); $i++)
			foreach ($_SESSION['cart']->items as $item)
				if ( $product_arr[$i]['CONTENT_ID'] == $item['id']  && !$item['status']) {
					$product_arr[$i]['_productUrl'] = $this -> getProductUrl($product_arr[$i]['CONTENT_ID']);;
					$product_arr[$i]['_quantity'] = $item['quantity'];
					$full_cost += ((int)$item["quantity"])*$product_arr[$i]["PRICE"];
		  			$product_arr[$i]['_cost'] = $this -> getPrice(((int)$item['quantity'])*$product_arr[$i]['PRICE']);
		  			$product_arr[$i]['PRICE'] = $this -> getPrice($product_arr[$i]['PRICE']);
				}
		
		$this -> tmpl -> setLoop('_productLoop', $product_arr);
		$totalAmount = $this -> getPrice($full_cost);
	  	$this -> tmpl->setVar( "_full_cost", $totalAmount );
		$totalAmount = $this -> getPrice($full_cost, 'main');
  		$this -> tmpl->setVar( "_full_costMain", $totalAmount );
  		$this -> tmpl->setVar( "_mainCurrency", $this -> mainCurrency['NAME_SHORT'] );
	  	$this -> tmpl->setVar( "_publishedCurrency", $this -> publishedCurrency['NAME_SHORT'] );
	
		//Если есть блок с модулем корзина и он инициализируется раньше модуля "Оформить заказ"
		$basket_tarea_arr = sql_select("select
										      TA.TEMPLATE_AREA_ID AS TAREA_ID
										from
										    PRG_MODULE PM,
										    INF_BLOCK IB,
										    PAGE_AREA PA,
										    TEMPLATE_AREA TA
										where
										     PM.CLASS_NAME = 'basket' and
										     PM.PRG_MODULE_ID = IB.PRG_MODULE_ID and
										     IB.INF_BLOCK_ID = PA.INF_BLOCK_ID and
										     PA.PAGE_ID = " . intval($this -> page_id) . " and
										     PA.VERSION = " . intval($this -> version) . " and
										     PA.TEMPLATE_AREA_ID = TA.TEMPLATE_AREA_ID");
	
		$this -> tmpl -> setLoop('_basketTAreaLoop', $basket_tarea_arr);		

	if ( !$this -> q_param['is_agree']) return false;
	
	// ОФОРМЛЕНИЕ ЗАКАЗА
	
	$order_status_id = sql_select("select ORDER_STATUS_ID from ORDER_STATUS where IS_FIRST = 1");

	// Сохраняется заказа
	insert_record_with_type('ORDERS', array(
			array( name => 'CLIENT_ID', value => intval($this -> client_id)),
			array( name => 'FIO', value => htmlspecialchars($_SESSION['order']->fio, ENT_QUOTES)),
			array( name => 'ADDRESS', value => htmlspecialchars($_SESSION['order']->address, ENT_QUOTES)),
			array( name => 'TELEPHONE', value => htmlspecialchars($_SESSION['order']->telephone, ENT_QUOTES)),
			array( name => 'FAX', value => htmlspecialchars($_SESSION['order']->fax, ENT_QUOTES)),
			array( name => 'NOTE', value => htmlspecialchars($_SESSION['order']->note, ENT_QUOTES)),
			array( name => 'PAYMENT_ID', value => intval($_SESSION['order']->payment_id)),
			array( name => 'ORDER_STATUS_ID', value => intval($order_status_id[0]['ORDER_STATUS_ID'])),
			array( name => 'CURRENCY_SHOP_ID', value => intval($this -> mainCurrency['CURRENCY_SHOP_ID'] ? $this -> mainCurrency['CURRENCY_SHOP_ID'] : 0)),
			array( name => 'DATE_RECEIPT', value => date("Y").date("m").date("d").date("H").date("i").date("s"), type => 'datetime'),
			array( name => 'COMMENTS', value => htmlspecialchars($_SESSION['order']->comments, ENT_QUOTES)),
			array( name => 'TOTAL_SUM', value => $totalAmount)
	));

	// Сохраняется адрес доставки, если он новый
	if ( $_SESSION['order']->delivery_address_id <= 0 ) 
		insert_record_with_type('DELIVERY_ADDRESS', array(
				array( name => 'CLIENT_ID', value => intval($this -> client_id)),
				array( name => 'FIO', value => htmlspecialchars($_SESSION['order']->fio, ENT_QUOTES)),
				array( name => 'ADDRESS', value => htmlspecialchars($_SESSION['order']->address, ENT_QUOTES)),
				array( name => 'TELEPHONE', value => htmlspecialchars($_SESSION['order']->telephone, ENT_QUOTES)),
				array( name => 'FAX', value => htmlspecialchars($_SESSION['order']->fax, ENT_QUOTES)),
				array( name => 'NOTE', value => htmlspecialchars($_SESSION['order']->note, ENT_QUOTES))
		));
	
	// Сохраняется состав заказа
	$orders_id = sql_select("select MAX(ORDERS_ID) as ID from ORDERS where CLIENT_ID = " . intval($this -> client_id));

	foreach ($product_arr as $item)
		insert_record('ORDER_ITEM', array(
				array( name => 'ORDERS_ID', value => intval($orders_id[0]['ID'])),
				array( name => 'CONTENT_ID', value => intval($item['CONTENT_ID'])),
				array( name => 'NAME', value => $item['TITLE']),
				array( name => 'QUANTITY', value => intval($item['_quantity'])),
				array( name => 'PRICE', value => $this -> getPrice($item['PRICE'], 'main'))
		));

	$client = sql_select("select * from CLIENT where CLIENT_ID = ".intval($this -> client_id)." and RANDOM_NUMBER = ".floatval($_COOKIE['random_number']));
	
    $fileTMPL = "{$this -> path_tmpl}noticeLetter.vtmpl";
    
    // Формируется тело письма для менеджера и клиента
    if (!file_exists($fileTMPL)) $htmlBodyToManager = "Шаблон отсутствует: $fileTMPL";
  	else {
	    $order = sql_select("select *, P.NAME as PAYMENT_NAME from ORDERS O, PAYMENT P 
	    					 where 
	    					 	O.ORDERS_ID = ".intval($orders_id[0]['ID'])." and 
	    					 	O.PAYMENT_ID = P.PAYMENT_ID and
	    					 	P.LANG_ID = ".intval($this -> lang_id) );
		
		$order[0]['PRODUCT_LOOP'] 		= $product_arr;
		$order[0]['_full_cost'] 		= $this -> getPrice($full_cost);
		$order[0]['_full_costMain'] 	= $this -> getPrice($full_cost, 'main');
		$order[0]['_publishedCurrency'] = $this -> publishedCurrency['NAME_SHORT'];
		$order[0]['_mainCurrency'] 		= $this -> mainCurrency['NAME_SHORT'];
		$order[0]['_host'] 				= $_SERVER['HTTP_HOST'];

  		$htmlBody = new vlibTemplate();
		
		$htmlBody -> newTemplate($fileTMPL);
		$htmlBody -> hash2vlib($order[0]);
		$htmlBodyToManager = $htmlBody -> grab();
		
		$htmlBody -> newTemplate($fileTMPL);
		$htmlBody -> setVar('toClient', 1);
		$htmlBodyToClient = $htmlBody -> grab();
  	}
  	
	$param = array( 'to' 		=> $client[0]['EMAIL'],
					'toName'   	=> "{$client[0]['SURNAME']} {$client[0]['NAME']} {$client[0]['PATRONYMIC']}",
					'from'		=> 'webmaster@'.$_SERVER['HTTP_HOST'],
					'fromName'	=> 'Система оформления заказа',
					'subject'	=> 'Ваш заказ поступил в магазин '.$_SERVER['HTTP_HOST'],
					'htmlBody'	=> $htmlBodyToClient);

	// Отсылается уведомление клиенту
	$this -> sendMail($param);

	$param['toName']	= 'Уважаемый администратор!';
	$param['subject'] 	= 'В магазин поступил новый заказ';
	$param['htmlBody'] 	= $htmlBodyToManager;
	
	// Отсылается уведомление менеджеру
	if ($mailArr = preg_split("/[,; ]+/", $this -> view_param['email'])) {

 		for	($i = 0; $i < count($mailArr); $i++) {

 			if (preg_match('/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9_-]+(\.[_a-z0-9-]+)+$/i', $mailArr[$i])) {

	 			$param['to'] = $mailArr[$i];
				$this -> sendMail($param);
			}
		}
	}
	
	//Очистка корзины
	$tmp = array();
	foreach ( $_SESSION['cart']->items as $item )
		if ( $item['status'] ) $tmp[] = $item;
	
	$_SESSION['cart']->items = $tmp;
	$_SESSION['order'] = new order;
	
	return true;
  }

  /***************************** Шаг 2 *******************/
  function step2() {
  
  	$delivery_address_arr = sql_select("select * from DELIVERY_ADDRESS where CLIENT_ID = " . intval($this -> client_id));
	
	//Список известных адресов пуст.
	if ( !count($delivery_address_arr) ) $this -> tmpl -> setVar( "_is_empty", 1);
	
	$delivery_address_arr[] = array( 'DELIVERY_ADDRESS_ID' => 0 );

	//Проверка адреса
	if ( isset($this -> q_param['delivery_address_id']) && is_numeric($this -> q_param['delivery_address_id']) ) {
		
		$delivery_address_id = sql_select("select * from DELIVERY_ADDRESS where DELIVERY_ADDRESS_ID = " . intval($this -> q_param['delivery_address_id']));

		//Известный адрес
		if ( count($delivery_address_id) ) {

			$is_right_address = true;
			$_SESSION['order']->delivery_address_id = $delivery_address_id[0]['DELIVERY_ADDRESS_ID'];
			$_SESSION['order']->fio = $delivery_address_id[0]['FIO'];
			$_SESSION['order']->telephone = $delivery_address_id[0]['TELEPHONE'];
			$_SESSION['order']->fax = $delivery_address_id[0]['FAX'];
			$_SESSION['order']->address = $delivery_address_id[0]['ADDRESS'];
			$_SESSION['order']->note = $delivery_address_id[0]['NOTE'];
		} else {

			$is_right_address = true;
			if ( !trim($this -> q_param['telephone'], ' ') || !trim($this -> q_param['address'], ' ') ) {
				$this -> tmpl -> setVar( "_is_error", 1);
				$is_right_address = false;
			}
			
			if ( !trim($this -> q_param['fio'], ' ') ) {
				$client_id = sql_select("select * from CLIENT where CLIENT_ID = " . intval($this -> client_id));
				$_SESSION['order']->fio = $client_id[0]['SURNAME'] . ' ' . $client_id[0]['NAME'] . ' ' . $client_id[0]['PATRONYMIC'];
			} else $_SESSION['order']->fio = $this -> q_param['fio'];
			
			$_SESSION['order']->delivery_address_id = $this -> q_param['delivery_address_id'];
			$_SESSION['order']->telephone = $this -> q_param['telephone'];
			$_SESSION['order']->fax = $this -> q_param['fax'];
			$_SESSION['order']->address = $this -> q_param['address'];
			$_SESSION['order']->note = $this -> q_param['note'];
		}
	}

  	if ( !isset($_SESSION['order']->delivery_address_id) ) $delivery_address_arr[0]['_checked'] = 1;
	else {
		for ( $i = 0; $i < count($delivery_address_arr); $i++ )
			if ( $delivery_address_arr[$i]['DELIVERY_ADDRESS_ID'] == $_SESSION['order']->delivery_address_id ) {
				$delivery_address_arr[$i]['_checked'] = 1;
				//Другой адрес
				if ( $delivery_address_arr[$i]['DELIVERY_ADDRESS_ID'] == 0 ) {

					$delivery_address_arr[$i]['FIO'] = $_SESSION['order']->fio;
					$delivery_address_arr[$i]['TELEPHONE'] = $_SESSION['order']->telephone;
					$delivery_address_arr[$i]['FAX'] = $_SESSION['order']->fax;
					$delivery_address_arr[$i]['ADDRESS'] = $_SESSION['order']->address;
					$delivery_address_arr[$i]['NOTE'] = $_SESSION['order']->note;
					$delivery_address_arr[$i]['_is_empty'] = 1;
				}
			}
	}
  	
  	$this -> tmpl -> setLoop( "_delivery_address_loop", $delivery_address_arr);

	if ( !$is_right_address ) return false;

	$_SESSION['order']->step = 3;

	return true;
  }
  
  /***************************** Шаг 1 *******************/
  function step1() {
  	
  	$payment_arr = sql_select("select * from PAYMENT where IS_ACTIVE = 1 and LANG_ID = ".intval($this -> lang_id)." order by PAYMENT_ORDER");

  	if ( !isset($_SESSION['order']->payment_id) ) $payment_arr[0]['_checked'] = 1;
  	else 
  		for ( $i = 0; $i < count($payment_arr); $i++ )
  			if ( $payment_arr[$i]['PAYMENT_ID'] == $_SESSION['order']->payment_id ) $payment_arr[$i]['_checked'] = 1;
  	
  	$this -> tmpl -> setLoop( "_payment_loop", $payment_arr);

  	$payment_id = ($this -> q_param['payment_id'] ? sql_select("select * from PAYMENT where payment_id = " . intval($this -> q_param['payment_id'])) : array());

  	if ( !$this -> q_param['payment_id'] || !count($payment_id) ) return false;

    $_SESSION['order']->payment_id = $this -> q_param['payment_id'];
    $_SESSION['order']->payment_name = $payment_id[0]['NAME'];  	
  	$_SESSION['order']->step = 2;

  	return true;
  }

  /**
   * Отключается кэширование модуля
   * @return boolean
   */
  function get_hash_code() {return false;}

}
?>